package wt.geeks;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.StringJoiner;
/**
 * https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
 */
public final class SmallestK {

    static class BitNode {
        int num = 0;
        int maxv = 0;
        int minv = 0;
        int val;
        boolean isLeaf = false;
        BitNode succecor = null;
        BitNode left = null;
        BitNode right = null;
    }
    private BitNode root, headLeaf;
    int[] sortArray = null;
    int maxDepth = 32;
    final int arrayLen;
    public SmallestK(int[] array) {
        root = new BitNode();
        if (array != null) {
            arrayLen = array.length;
            if (arrayLen < 32) {
                Arrays.sort(array);
                sortArray = array;
            } else {
                int maxVal = -Integer.MAX_VALUE;
                for (int i : array) {
                    maxVal = i > maxVal ? i : maxVal;
                }
                maxDepth = (int)(Math.log(maxVal)/Math.log(2)) + 1;
                for (int i : array) {
                    insertValue(this.root, i, 0, null, null);
                }
                BitNode curNode = headLeaf;
                sortArray = new int[arrayLen];
                int i = 0;
                while (curNode != null && i < arrayLen) {
                    sortArray[i++] = curNode.val;
                    curNode = curNode.succecor;
                }
            }
        } else {
            arrayLen = 0;
        }
    }

    private void insertValue(BitNode root, int v, int depth,
            BitNode suc, BitNode pred) {
        if (depth == maxDepth) {
            root.val = v;
            root.isLeaf = true;
            root.num += 1;
            root.minv = root.maxv = v;
            // down road to the leaf, suc try to find left-most,
            // pred try to find right-most
            while(suc != null && !suc.isLeaf) {
                if (suc.left != null && suc.left.maxv > v) {
                    suc = suc.left;
                } else {
                    suc = suc.right;
                }
            }
            while(pred != null && !pred.isLeaf) {
                if (pred.right != null && pred.right.minv < v) {
                    pred = pred.right;
                } else {
                    pred = pred.left;
                }
            }
            if (suc != null) {
                root.succecor = suc;
            }
            if (pred != null) {
                pred.succecor = root;
            } else {
                headLeaf = root;
            }
        } else {
            if (root.num > 0) {
                if (root.left != null) {
                    if (root.left.minv < v) {
                        pred = root.left;
                    }
                }
                if (root.right != null) {
                    if (root.right.maxv > v) {
                        suc = root.right;
                    }
                }
            }
            root.num += 1;
            if (root.num == 1) {
                root.minv = root.maxv = v;
            } else {
                if (root.minv > v) {
                    root.minv = v;
                }
                if (root.maxv < v) {
                    root.maxv = v;
                }
            }
            int bit = (v >> (maxDepth - depth - 1)) & 1;
            if (bit == 0) {
                if (root.left == null) {
                    root.left = new BitNode();
                }
                insertValue(root.left, v, depth + 1, suc, pred);
            } else {
                if (root.right == null) {
                    root.right = new BitNode();
                }
                insertValue(root.right, v, depth + 1, suc, pred);
            }
        }
    }

    public int findK(int k) {
        if (k < 1) {
            throw new IllegalAccessError("K must greater than 1, input: " + k);
        }
        return sortArray[k-1];
    }
    /**
     * Says hello to the world.
     * @param args The arguments of the program.
     */
    public static void main(String[] args) {
        Random rnd = new Random(3263);
        final int arrayLen = 5000;
        for (int n = 0; n < 1000; ++n) {
            Set<Integer> dedup = new HashSet<>();
            int[] array = new int[arrayLen];
            StringJoiner sj = new StringJoiner(", ", "[", "]");
            for (int i = 0; i < arrayLen; ++i) {
                int a = rnd.nextInt(100000);
                while (dedup.contains(a)) {
                    a = rnd.nextInt(100000);
                }
                dedup.add(a);
                array[i] = a;
                sj.add("" + a);
            }
            SmallestK smallestK = new SmallestK(array);
            Arrays.sort(array);
            final int k = rnd.nextInt(arrayLen) + 1;
            String orgArray = sj.toString();
            sj = new StringJoiner(", ", "[", "]");
            for (int i : array) {
                sj.add("" + i);
            }

            System.out.println(String.format("array: %s,\nsorted: %s,\ntop k = %d, expect result = %d", orgArray,
                    sj.toString(), smallestK.findK(k), array[k - 1]));
            if (smallestK.findK(k) != array[k - 1]) {
                System.out.println(">>>> Failed, k = " + k);
                break;
            }
        }
    }
}
